package com.zhang;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class MyCache{//资源类
    private volatile Map map= new HashMap();
    private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
    public void put(String key,Object value){//写操作
        try {
            rwLock.writeLock().lock();
            System.out.println("线程名："+Thread.currentThread().getName() + "\t正在写入"+key);
            TimeUnit.MILLISECONDS.sleep(300);
            map.put(key,value);
            System.out.println("线程名："+Thread.currentThread().getName() + "\t写入完成");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rwLock.writeLock().unlock();
        }
    }

    public void get(String key){//读操作
        try {
            rwLock.readLock().lock();
            System.out.println("线程名："+Thread.currentThread().getName() + "\t正在读取"+key);
            TimeUnit.MILLISECONDS.sleep(300);
            Object result = map.get(key);
            System.out.println("线程名："+Thread.currentThread().getName() + "\t读取完成，结果"+result);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rwLock.readLock().unlock();
        }
    }

}

public class ReadWriteLockDemo {

    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        for (int i = 0; i <3 ; i++) {
            final int tempInt = i;
            new Thread(()->{
                myCache.put(String.valueOf(tempInt),String.valueOf(tempInt));
            },String.valueOf(i)).start();
        }

        for (int i = 0; i <3 ; i++) {
            final int tempInt = i;
            new Thread(()->{
                myCache.get(String.valueOf(tempInt));
            },String.valueOf(i)).start();
        }
    }


}
